<template>
  <div class="orders-container">
    <NavBar>
      <template #default>全部订单</template>
    </NavBar>

    <!-- 订单状态导航栏 -->
    <div class="status-nav">
      <div
        v-for="tab in statusTabs"
        :key="tab.value"
        class="status-tab"
        :class="{ 'active': currentStatus === tab.value }"
        @click="switchStatus(tab.value)"
      >
        {{ tab.label }}
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-content">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>

      <div v-else-if="orders.length === 0" class="empty-orders">
        <el-icon class="empty-icon"><DocumentRemove /></el-icon>
        <p>暂无相关订单</p>
      </div>

      <div v-else class="orders-list">
        <div
          v-for="order in orders"
          :key="order.orderId"
          class="order-card"
          @click="goToOrderDetail(order.orderId)"
        >
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="order-info">
              <span class="order-number">订单号：{{ order.orderId }}</span>
              <span class="order-time">{{ formatOrderTime(order.updateTime) }}</span>
            </div>
            <div class="order-status" :class="getOrderStatusColor(order.orderStatus)">
              {{ getOrderStatusText(order.orderStatus) }}
            </div>
          </div>

          <!-- 订单商品列表 -->
          <div class="order-items">
            <div
              v-for="item in order.orderItems"
              :key="item.orderItemId"
              class="order-item"
            >
              <img :src="formatImageUrl(item.mainImage)" :alt="item.productName" class="item-image" />
              <div class="item-details">
                <h4 class="item-name">{{ item.productName }}</h4>
                <div class="item-price-quantity">
                  <span class="item-price">￥{{ formatPrice(item.price) }}</span>
                  <span class="item-quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单底部 -->
          <div class="order-footer">
            <div class="order-total">
              <span class="total-label">共{{ order.totalQuantity }}件商品 </span>
              <span class="total-amount">合计：￥{{ formatPrice(order.totalAmount) }}</span>
            </div>
            <div class="order-actions">
              <el-button
                v-if="order.orderStatus === ORDER_STATUS.PENDING_PAYMENT"
                type="primary"
                size="small"
                @click.stop="payOrder(order)"
              >
                立即支付
              </el-button>
              <el-button
                v-if="order.orderStatus === ORDER_STATUS.SHIPPED"
                type="primary"
                size="small"
                @click.stop="confirmReceive(order)"
              >
                确认收货
              </el-button>
              <el-button
                v-if="order.orderStatus === ORDER_STATUS.COMPLETED"
                size="small"
                @click.stop="goToReview(order)"
              >
                去评价
              </el-button>
              <el-button
                size="small"
                @click.stop="goToOrderDetail(order.orderId)"
              >
                查看详情
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载更多提示 -->
      <div v-if="orders.length > 0" class="load-more-container">
        <div v-if="loadingMore" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载更多...</span>
        </div>
        <div v-else-if="hasNoMore" class="no-more">
          <span>没有更多订单了</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading, DocumentRemove } from '@element-plus/icons-vue';
import NavBar from '../../components/common/NavBar.vue';
import {
  getOrdersListAPI,
  ORDER_STATUS,
  getOrderStatusText,
  getOrderStatusColor
} from '@/api/OrderApi';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 响应式数据
const orders = ref([]);
const loading = ref(false);
const loadingMore = ref(false);
const hasNoMore = ref(false);
const currentStatus = ref(null); // null表示全部订单
const currentPage = ref(1);
const pageSize = ref(10);

// 订单状态导航配置
const statusTabs = [
  { label: '全部', value: null },
  { label: '待支付', value: ORDER_STATUS.PENDING_PAYMENT },
  { label: '待发货', value: ORDER_STATUS.PAID_PENDING_SHIP },
  { label: '待收货', value: ORDER_STATUS.SHIPPED },
  { label: '退款/退货', value: ORDER_STATUS.REFUNDED },
  { label: '评价', value: ORDER_STATUS.COMPLETED }
];

// 获取订单列表
const fetchOrders = async (isLoadMore = false) => {
  if (!userStore.userInfo?.userId) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  // 设置加载状态
  if (isLoadMore) {
    loadingMore.value = true;
  } else {
    loading.value = true;
    currentPage.value = 1;
    hasNoMore.value = false;
  }

  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };

    // 如果有选择状态，添加到参数中
    if (currentStatus.value !== null) {
      params.orderStatus = currentStatus.value;
    }

    const response = await getOrdersListAPI(params);

    if (response.data.code === 1) {
      const responseData = response.data.data;
      let newOrders = [];

      // 解析返回的数据
      if (responseData && typeof responseData === 'object' && responseData.records) {
        // 如果后端返回了分页格式: {records: [], total: 100, current: 1, size: 10}
        newOrders = responseData.records || [];
      } else if (responseData && Array.isArray(responseData)) {
        // 如果后端直接返回数组
        newOrders = responseData;
      }

      // 根据是否加载更多来处理数据
      if (isLoadMore) {
        // 追加新数据
        orders.value = [...orders.value, ...newOrders];
      } else {
        // 替换全部数据
        orders.value = newOrders;
      }

      // 判断是否还有更多数据
      if (newOrders.length < pageSize.value) {
        hasNoMore.value = true;
      }

      console.log('订单列表获取成功:', `第${currentPage.value}页`, newOrders.length, '条', isLoadMore ? '(追加)' : '(初始)');
    } else {
      throw new Error(response.data.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error(error.message || '获取订单列表失败');
    if (!isLoadMore) {
      orders.value = [];
    }
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 加载更多订单
const loadMoreOrders = () => {
  if (hasNoMore.value || loadingMore.value) return;

  currentPage.value++;
  fetchOrders(true);
};

// 切换订单状态
const switchStatus = (status) => {
  if (currentStatus.value === status) return;

  currentStatus.value = status;
  fetchOrders(); // 重置并加载新数据
};

// 格式化订单时间
const formatOrderTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化图片URL，处理反斜杠问题
const formatImageUrl = (url) => {
  if (!url) return '';
  // 将反斜杠替换为正斜杠
  return url.replace(/\\/g, '/');
};
// 当计算 390.15 * 3 时，JavaScript 会得到 1170.4499999999998 这样的结果，这是因为JavaScript使用IEEE 754标准的双精度浮点数来表示数字。
// 让我们修复这个问题，有两种解决方案：
// 使用 toFixed() 方法格式化显示
// 使用 Math.round() 四舍五入到指定小数位
// 格式化金额，处理精度问题
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  // 使用Number处理一下，以防传入的是字符串
  return Number(price).toFixed(2);
};

// 跳转到订单详情
const goToOrderDetail = (orderId) => {
  router.push(`/order/detail/${orderId}`);
};

// 跳转到支付页面
const payOrder = (order) => {
  router.push({
    path: '/payment',
    query: {
      orderId: order.orderId,
      amount: order.totalAmount,
      paymentType: 1 // 默认支付宝
    }
  });
};

// 确认收货
const confirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确认收到商品了吗？确认后订单将完成。',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'info',
      }
    );

    // 这里调用确认收货API
    ElMessage.success('确认收货成功');
    fetchOrders(); // 刷新订单列表
  } catch {
    // 用户取消操作
  }
};

// 去评价（暂时显示提示）
const goToReview = (order) => {
  ElMessage.info(`评价功能开发中，订单ID：${order.orderId}`);
  // router.push(`/order/review/${order.orderId}`); // 等评价页面开发完成后启用
};

// 滚动监听函数
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const windowHeight = window.innerHeight || document.documentElement.clientHeight;
  const documentHeight = document.documentElement.scrollHeight;

  // 距离底部50px时开始加载
  if (scrollTop + windowHeight >= documentHeight - 50) {
    loadMoreOrders();
  }
};

// 组件挂载时获取订单列表
onMounted(() => {
  // 检查URL参数中是否有状态
  const urlStatus = route.query.status;
  if (urlStatus !== undefined) {
    currentStatus.value = parseInt(urlStatus);
  }

  // 添加滚动监听
  window.addEventListener('scroll', handleScroll, { passive: true });

  fetchOrders();
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.orders-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 44px; /* NavBar高度 */
  padding-bottom: 60px; /* 底部导航栏高度 */
}

/* 状态导航栏 */
.status-nav {
  background: white;
  padding: 12px 16px;
  display: flex;
  gap: 12px;
  overflow-x: auto;
  white-space: nowrap;
  border-bottom: 1px solid #f0f0f0;
}

.status-tab {
  padding: 8px 16px;
  border-radius: 20px;
  background: #f5f5f5;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  flex-shrink: 0;
}

.status-tab.active {
  background: #ff5000;
  color: white;
}

.status-tab:hover {
  background: #ff7730;
  color: white;
}

.status-tab.active:hover {
  background: #e64500;
}

/* 订单内容区域 */
.orders-content {
  padding: 0 16px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-container .el-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

/* 空状态 */
.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 订单列表 */
.orders-list {
  padding-top: 12px;
}

.order-card {
  background: white;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-status {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 订单状态颜色 */
.status-pending {
  color: #ff5000;
  background: #fff5f0;
}

.status-paid {
  color: #1890ff;
  background: #f0f5ff;
}

.status-shipped {
  color: #52c41a;
  background: #f6ffed;
}

.status-completed {
  color: #722ed1;
  background: #f9f0ff;
}

.status-cancelled {
  color: #999;
  background: #f5f5f5;
}

.status-refunded {
  color: #fa541c;
  background: #fff2e8;
}

/* 订单商品列表 */
.order-items {
  margin-bottom: 12px;
}

.order-item {
  display: flex;
  gap: 12px;
  padding: 8px 0;
}

.order-item:not(:last-child) {
  border-bottom: 1px solid #f8f8f8;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  flex-shrink: 0;
}

.item-details {
  flex: 1;
  min-width: 0;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-price {
  color: #ff5000;
  font-size: 14px;
  font-weight: 500;
}

.item-quantity {
  color: #666;
  font-size: 14px;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.order-total {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.total-label {
  font-size: 12px;
  color: #666;
}

.total-amount {
  font-size: 16px;
  color: #ff5000;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 8px;
}

/* 加载更多提示 */
.load-more-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.loading-more {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.loading-more .el-icon {
  font-size: 16px;
}

.no-more {
  color: #999;
  font-size: 14px;
  text-align: center;
  padding: 10px 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .order-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .order-actions {
    justify-content: center;
  }
}
</style>